import datetime
import os
import time
from urllib.parse import quote

import xlwt
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect, StreamingHttpResponse
from django.shortcuts import render

# Create your views here.
from form.models import bks
from index.models import VStuShow, YJS, JZG, DW, Premissions, JwToRenshi, UserInfo
from index.utils import Department
from .models import bk_classroom, dep_count, bucket


class userModel:
    userid = None
    realname = None
    state = None
    phonenumber = "未知"
    residence = "未知"
    isinschool = "未知"
    location = "未知"
    isfever = "未知"
    is_go_to_outer = "未知"
    isplanedtravel = "未知"
    ispassed = "未知"
    trans_type = "未知"
    isseen = "未知"
    isisolated = "未知"
    hospital = "未知"
    is_atach_patient = "未知"
    folk_attach = "未知"
    planedtravel_time = "未知"
    plan_back_time = "未知"
    planedleave_time = "未知"

    def __init__(self, userid, realname, usertype):
        self.userid = userid
        self.realname = realname
        now = datetime.datetime.now().strftime("%Y-%m-%d")
        # todo: delete
        try:
            bks.objects.get(createdate__contains=now, userid=userid)
            self.state = "已提交"
        except ObjectDoesNotExist:
            self.state = "未提交"


class ClassModel:
    classid = None
    name = str()
    total = 0
    is_faver = 0
    submited = 0
    unsubmited = 0
    is_passed = 0
    is_deacted = 0
    is_attatch_patient = 0
    is_unsearch = 0
    isinschool = 0
    is_go_to_outer = 0
    isplanedtravel = 0
    folk_attach = 0
    usertype = None

    def __init__(self, classid, name, usertype):
        self.name = name
        self.classid = classid
        self.usertype = usertype


def anysis(request):
    context = dict()
    username = request.session.get("user", None)
    if username is None:
        return HttpResponseRedirect("../index/")
    usertype = request.session.get("user_type")
    try:
        Premissions.objects.get(userid=username, usertype=usertype)
        context["hasper"] = True
    except:
        context["hasper"] = False
    userlist = list()
    if usertype == 0:
        user = VStuShow.objects.db_manager("jw").get(username=username)
        classmate_list = VStuShow.objects.db_manager("jw").filter(class_id=user.class_id)
        for o in classmate_list:
            userlist.append(userModel(o.username, o.realname, usertype))
        # classmate_list = VStuShow.objects.filter(class_id=user.class_id)
    elif usertype == 1:
        user = YJS.objects.get(userid=username)
        classmate_list = YJS.objects.filter(depid=user.depid)
        for o in classmate_list:
            userlist.append(userModel(o.userid, o.realname, usertype))
    elif usertype == 2:
        user = JZG.objects.get(userid=username)
        root = Department(user.depid).getroot().idn
        dep_list = DW.objects.filter(parent=root)
        classmate_list = JZG.objects.filter(depid=root)
        for o in classmate_list:
            userlist.append(userModel(o.userid, o.realname, usertype))
        for dep in dep_list:
            classmate_list = JZG.objects.filter(depid=dep.bm)
            for o in classmate_list:
                userlist.append(userModel(o.userid, o.realname, usertype))

    context["user_list"] = userlist
    if username is None:
        return HttpResponseRedirect("../index/")
    return render(request, "anysis.html", context)


def show_detail(request):
    context = dict()
    username = request.session.get("user", None)
    if username is None:
        return HttpResponseRedirect("../index/")
    usertype = request.session.get("user_type")
    usertype1 = int(request.GET.get("usertype", -1))
    try:
        usr_per = Premissions.objects.get(userid=username, usertype=usertype)
    except:
        return render(request, "anysis_show.html", context)
    date = request.GET.get("date", datetime.datetime.now().strftime("%Y-%m-%d"))
    show_class_list = list()
    permission_type = eval(usr_per.permission_type)
    permission_dep = eval(usr_per.permission)[0]
    permission_class = eval(usr_per.permission)[1]
    depid = int(request.GET.get("depid", None))
    userlist = list()
    if usertype1 == 0:
        if ((depid in permission_class) and (3 in permission_type)) or (0 in permission_type) or (4 in permission_type):
            classmate_list = VStuShow.objects.db_manager("jw").filter(class_id=depid)
            for o in classmate_list:
                usr = userModel(o.username, o.realname, usertype1)
                try:
                    usrstate = bks.objects.get(createdate__contains=date, userid=o.username, usertype=0)
                    usrinfo = UserInfo.objects.get(userid=o.username, usertype=0)
                    usr.phonenumber = usrinfo.phonenumber
                    usr.residence = usrinfo.residence
                    usr.isinschool = usrstate.get_isinschool_display()
                    usr.location = usrstate.location
                    usr.isfever = usrstate.get_isfever_display()
                    usr.is_go_to_outer = usrstate.get_is_go_to_outer_display()
                    usr.isplanedtravel = usrstate.get_isplanedtravel_display()
                    usr.ispassed = usrstate.get_ispassed_display()
                    usr.trans_type = usrstate.get_trans_type_display()
                    usr.isseen = usrstate.get_isseen_display()
                    usr.isisolated = usrstate.get_isisolated_display()
                    usr.hospital = usrstate.hospital
                    usr.is_atach_patient = usrstate.get_is_atach_patient_display()
                    usr.folk_attach = usrstate.get_folk_attach_display()
                    usr.planedtravel_time = usrstate.planedtravel_time
                    usr.plan_back_time = usrstate.plan_back_time
                    usr.planedleave_time = usrstate.planedleave_time
                except ObjectDoesNotExist:
                    pass
                userlist.append(usr)
        else:
            return render(request, "anysis_show.html", context)
        context["user_list"] = userlist
        # classmate_list = VStuShow.objects.filter(class_id=user.class_id)
    elif usertype1 == 1:
        if depid in permission_dep:
            classmate_list = YJS.objects.filter(depid=depid)
            for o in classmate_list:
                usr = userModel(o.userid, o.realname, usertype1)
                try:
                    usrstate = bks.objects.get(createdate__contains=date, userid=o.userid, usertype=1)
                    usrinfo = UserInfo.objects.get(userid=o.userid, usertype=1)
                    usr.phonenumber = usrinfo.phonenumber
                    usr.residence = usrinfo.residence
                    usr.isinschool = usrstate.get_isinschool_display()
                    usr.location = usrstate.location
                    usr.isfever = usrstate.get_isfever_display()
                    usr.is_go_to_outer = usrstate.get_is_go_to_outer_display()
                    usr.isplanedtravel = usrstate.get_isplanedtravel_display()
                    usr.ispassed = usrstate.get_ispassed_display()
                    usr.trans_type = usrstate.get_trans_type_display()
                    usr.isseen = usrstate.get_isseen_display()
                    usr.isisolated = usrstate.get_isisolated_display()
                    usr.hospital = usrstate.hospital
                    usr.is_atach_patient = usrstate.get_is_atach_patient_display()
                    usr.folk_attach = usrstate.get_folk_attach_display()
                    usr.planedtravel_time = usrstate.planedtravel_time
                    usr.plan_back_time = usrstate.plan_back_time
                    usr.planedleave_time = usrstate.planedleave_time
                except ObjectDoesNotExist:
                    pass
                userlist.append(usr)
        else:
            return render(request, "anysis_show.html", context)
        context["user_list"] = userlist
    elif usertype1 == 2:
        root = Department(depid).getroot().idn
        if root in permission_dep:
            dep_list = DW.objects.filter(parent=root)
            classmate_list = JZG.objects.filter(depid=root)
            for o in classmate_list:
                usr = userModel(o.userid, o.realname, 2)
                try:
                    usrstate = bks.objects.get(createdate__contains=date, userid=o.userid, usertype=2)
                    usrinfo = UserInfo.objects.get(userid=o.userid, usertype=2)
                    usr.phonenumber = usrinfo.phonenumber
                    usr.residence = usrinfo.residence
                    usr.isinschool = usrstate.get_isinschool_display()
                    usr.location = usrstate.location
                    usr.isfever = usrstate.get_isfever_display()
                    usr.is_go_to_outer = usrstate.get_is_go_to_outer_display()
                    usr.isplanedtravel = usrstate.get_isplanedtravel_display()
                    usr.ispassed = usrstate.get_ispassed_display()
                    usr.trans_type = usrstate.get_trans_type_display()
                    usr.isseen = usrstate.get_isseen_display()
                    usr.isisolated = usrstate.get_isisolated_display()
                    usr.hospital = usrstate.hospital
                    usr.is_atach_patient = usrstate.get_is_atach_patient_display()
                    usr.folk_attach = usrstate.get_folk_attach_display()
                    usr.planedtravel_time = usrstate.planedtravel_time
                    usr.plan_back_time = usrstate.plan_back_time
                    usr.planedleave_time = usrstate.planedleave_time
                except ObjectDoesNotExist:
                    pass
                userlist.append(usr)
            for dep in dep_list:
                classmate_list = JZG.objects.filter(depid=dep.bm)
                for o in classmate_list:
                    usr = userModel(o.userid, o.realname, 1)
                    try:
                        usrstate = bks.objects.get(createdate__contains=date, userid=o.userid, usertype=1)
                        usrinfo = UserInfo.objects.get(userid=o.userid, usertype=1)
                        usr.phonenumber = usrinfo.phonenumber
                        usr.isinschool = usrinfo.get_isinschool_display()
                        usr.residence = usrinfo.residence
                        usr.location = usrstate.location
                        usr.ispassed = usrstate.get_ispassed_display()
                        usr.isfaver = usrstate.get_isfever_display()
                        usr.startdate = usrstate.startdate
                        usr.isseen = usrstate.get_isseen_display()
                        usr.hospital = usrstate.hospital
                        usr.isisolated = usrstate.get_isisolated_display()
                    except ObjectDoesNotExist:
                        pass
                    userlist.append(usr)
            context["user_list"] = userlist
        else:
            return render(request, "anysis_show.html", context)
    elif usertype1 == 5:
        root = Department(depid).getroot().idn
        try:
            depid = JwToRenshi.objects.get(renshi_bm=root).jwbm
        except ObjectDoesNotExist:
            depid = 0
        class_list = bk_classroom.objects.filter(depid=depid)
        for single in class_list:
            single_batch = ClassModel(single.classid, single.class_filed, 0)
            if single.total is None:
                single.total = single_batch.total = VStuShow.objects.db_manager("jw").filter(
                    class_id=single.classid).count()
                single.save()
            else:
                single_batch.total = single.total
            if single_batch.total is not 0:
                dates = bks.objects.filter(depid=single.classid, createdate__contains=date, usertype=0)
                for state in dates:
                    if state.isfever is True:
                        single_batch.is_faver += 1
                    if state.ispassed is not "3":
                        single_batch.is_passed += 1
                    if state.isseen is "2":
                        single_batch.is_deacted += 1
                single_batch.submited = dates.count()
                single_batch.unsubmited = single_batch.total - single_batch.submited
                show_class_list.append(single_batch)
        context["class_list"] = show_class_list

    if username is None:
        return HttpResponseRedirect("../index/")
    return render(request, "anysis_show.html", context)


def show(request):
    context = dict()
    username = request.session.get("user", None)
    if username is None:
        return HttpResponseRedirect("../index/")
    usertype = int(request.session.get("user_type", None))
    try:
        usr_per = Premissions.objects.get(userid=username, usertype=usertype)
    except:
        return render(request, "anysis_show.html", context)
    date = request.GET.get("date", None)
    show_class_list = list()
    permission_dep = eval(usr_per.permission)[0]
    permission_class = eval(usr_per.permission)[1]
    if date is None:
        date = datetime.datetime.now().strftime("%Y-%m-%d")
    if 1 in eval(usr_per.permission_type):
        for depid in permission_dep:
            single_batch = ClassModel(Department(depid).getroot().idn, Department(depid).getroot().name + " (研究生)", 1)
            try:
                dep = dep_count.objects.get(depid=Department(depid).getroot().idn, usertype=1)
            except ObjectDoesNotExist:
                dep = dep_count.objects.create(depid=Department(depid).getroot().idn, usertype=1)
            if dep.total is None:
                dep.total = YJS.objects.filter(depid=Department(depid).getroot().idn).count()
                dep_list = DW.objects.filter(parent=Department(depid).getroot().idn)
                for dep_b in dep_list:
                    dep.total += YJS.objects.filter(depid=dep_b.bm).count()
                dep.save()
            if dep.total is not 0:
                single_batch.total = dep.total
                dates = bks.objects.filter(depid=Department(depid).getroot().idn, createdate__contains=date,
                                           usertype=1)
                for state in dates:
                    if state.isfever is True:
                        single_batch.is_faver += 1
                    if state.ispassed is not "3":
                        single_batch.is_passed += 1
                    if state.isseen is "2":
                        single_batch.is_deacted += 1
                single_batch.submited = dates.count()
                single_batch.unsubmited = single_batch.total - single_batch.submited
                show_class_list.append(single_batch)
    if 2 in eval(usr_per.permission_type):
        print("查看教职工")
        for depid in permission_dep:
            single_batch = ClassModel(Department(depid).getroot().idn, Department(depid).getroot().name + " (教职工)", 2)
            try:
                dep = dep_count.objects.get(depid=Department(depid).getroot().idn, usertype=2)
            except ObjectDoesNotExist:
                dep = dep_count.objects.create(depid=Department(depid).getroot().idn, usertype=2)
            if dep.total is None:
                dep.total = JZG.objects.filter(depid=Department(depid).getroot().idn).count()
                dep_list = DW.objects.filter(parent=Department(depid).getroot().idn)
                for dep_b in dep_list:
                    dep.total += JZG.objects.filter(depid=dep_b.bm).count()
                dep.save()
            if dep.total is not 0:
                single_batch.total = dep.total
                dates = bks.objects.filter(depid=Department(depid).getroot().idn, createdate__contains=date, usertype=2)
                for state in dates:
                    if state.isfever is True:
                        single_batch.is_faver += 1
                    if state.ispassed is not "3":
                        single_batch.is_passed += 1
                    if state.isseen is "2":
                        single_batch.is_deacted += 1
                single_batch.submited = dates.count()
                single_batch.unsubmited = single_batch.total - single_batch.submited
                show_class_list.append(single_batch)
    if 0 in eval(usr_per.permission_type):
        for depid in permission_dep:
            try:
                depid = JwToRenshi.objects.get(renshi_bm=depid).jwbm
            except ObjectDoesNotExist:
                depid = 0
            class_list = bk_classroom.objects.filter(depid=depid)
            for single in class_list:
                single_batch = ClassModel(single.classid, single.class_filed, 0)
                if single.total is None:
                    single.total = single_batch.total = VStuShow.objects.db_manager("jw").filter(
                        class_id=single.classid).count()
                    single.save()
                else:
                    single_batch.total = single.total
                if single_batch.total is not 0:
                    dates = bks.objects.filter(depid=single.classid, createdate__contains=date, usertype=0)
                    for state in dates:
                        if state.isfever is True:
                            single_batch.is_faver += 1
                        if state.ispassed is not "3":
                            single_batch.is_passed += 1
                        if state.isseen is "2":
                            single_batch.is_deacted += 1
                    single_batch.submited = dates.count()
                    single_batch.unsubmited = single_batch.total - single_batch.submited
                    show_class_list.append(single_batch)
    if 4 in eval(usr_per.permission_type):
        now = datetime.datetime.now().strftime("%Y-%m-%d")
        for depid in permission_dep:
            try:
                jwbm = JwToRenshi.objects.get(renshi_bm=depid).jwbm
            except ObjectDoesNotExist:
                jwbm = 0
            class_list = bk_classroom.objects.filter(depid=jwbm)
            single_batch = ClassModel(Department(depid).getroot().idn, Department(depid).getroot().name + " (本科生)", 5)
            for single in class_list:
                if single.total is None:
                    single.total = VStuShow.objects.db_manager("jw").filter(
                        class_id=single.classid).count()
                    single.save()
                single_batch.total += single.total
            if single_batch.total is not 0:
                try:
                    dates = bucket.objects.get(depid=Department(depid).getroot().idn, usertype=0,
                                               createdate__contains=now)
                    single_batch.is_faver = len(list(eval(dates.is_faver)))
                    single_batch.ispassed = len(list(eval(dates.is_passed)))
                    single_batch.is_deacted = len(list(eval(dates.is_deacted)))
                    single_batch.folk_attach = len(list(eval(dates.folk_attach)))
                    single_batch.is_unsearch = len(list(eval(dates.is_unsearch)))
                    single_batch.isinschool = len(list(eval(dates.isinschool)))
                    single_batch.is_go_to_outer = len(list(eval(dates.is_go_to_outer)))
                    single_batch.isplanedtravel = len(list(eval(dates.isplanedtravel)))
                    single_batch.is_attatch_patient = len(list(eval(dates.is_atach_patient)))
                    single_batch.submited = len(list(eval(dates.submited)))
                    single_batch.unsubmited = single_batch.total - single_batch.submited
                    show_class_list.append(single_batch)
                except ObjectDoesNotExist:

                    single_batch.unsubmited = single_batch.total - single_batch.submited
                    show_class_list.append(single_batch)

    if 3 in eval(usr_per.permission_type):
        class_list = permission_class
        for clid in class_list:
            single = bk_classroom.objects.get(classid=clid)
            single_batch = ClassModel(single.classid, single.class_filed, 0)
            if single.total is None:
                single.total = single_batch.total = VStuShow.objects.db_manager("jw").filter(
                    class_id=single.classid).count()
                single.save()
            else:
                single_batch.total = single.total
            if single_batch.total is not 0:
                dates = bks.objects.filter(depid=single.classid, createdate__contains=date, usertype=0)
                for state in dates:
                    if state.isfever is True:
                        single_batch.is_faver += 1
                    if state.ispassed is not "3":
                        single_batch.is_passed += 1
                    if state.isseen is "2":
                        single_batch.is_deacted += 1
                single_batch.submited = dates.count()
                single_batch.unsubmited = single_batch.total - single_batch.submited
                show_class_list.append(single_batch)
    context["class_list"] = show_class_list
    return render(request, "anysis_show.html", context)


def export(request):
    book = xlwt.Workbook()  # 新建工作簿
    sheet = book.add_sheet('export_info')  # 添加工作页
    context = dict()
    targets = request.POST.getlist("items")
    target_id = list()
    date = request.POST.get("date", datetime.datetime.now().strftime("%Y-%m-%d"))
    userlist = list()
    dep_list = ["学（工）号", "姓名", '是否已提交', '联系电话', '目前是否在校', '现居住地', '目前所在地区', '是否接触确诊病患',
                '是否有直系亲属确诊', '是否到疫区', '到达日期', '（预计）离开日期', '是否有发热、乏力、咳嗽、呼吸困难等症状', '就诊情况', '隔离情况', '就诊医院', '是否计划外出',
                '是否有返校计划', '返校计划搭乘的交通工具', '返校计划时间']
    now = datetime.datetime.now()
    now = str(time.mktime(now.timetuple()))
    userlist.append(dep_list)
    for target in targets:
        target = str(target).split("+")
        target_id = target[0]
        target_type = int(target[1])
        print(target_type)
        if target_type is 0:
            single_batch = VStuShow.objects.db_manager('jw').filter(class_id=target_id)
            for o in single_batch:
                usr = userModel(o.username, o.realname, 0)
                try:
                    usrstate = bks.objects.get(createdate__contains=date, userid=o.username, usertype=target_type)
                    usrinfo = UserInfo.objects.get(userid=o.username, usertype=target_type)
                    usr.phonenumber = usrinfo.phonenumber
                    usr.residence = usrinfo.residence
                    usr.isinschool = usrstate.get_isinschool_display()
                    usr.location = usrstate.location
                    usr.isfever = usrstate.get_isfever_display()
                    usr.is_go_to_outer = usrstate.get_is_go_to_outer_display()
                    usr.isplanedtravel = usrstate.get_isplanedtravel_display()
                    usr.ispassed = usrstate.get_ispassed_display()
                    usr.trans_type = usrstate.get_trans_type_display()
                    usr.isseen = usrstate.get_isseen_display()
                    usr.isisolated = usrstate.get_isisolated_display()
                    usr.hospital = usrstate.hospital
                    usr.is_atach_patient = usrstate.get_is_atach_patient_display()
                    usr.folk_attach = usrstate.get_folk_attach_display()
                    usr.planedtravel_time = usrstate.planedtravel_time
                    usr.plan_back_time = usrstate.plan_back_time
                    usr.planedleave_time = usrstate.planedleave_time
                except ObjectDoesNotExist:
                    pass
                userlist.append(usr)
        if target_type is 3:
            print("本科生")
            try:
                depid = JwToRenshi.objects.get(renshi_bm=target_id).jwbm
            except ObjectDoesNotExist:
                depid = 0
            class_list = bk_classroom.objects.filter(depid=depid)
            print(class_list)
            for single in class_list:
                single_batch = VStuShow.objects.filter(class_id=single.classid)
                for o in single_batch:
                    usr = userModel(o.username, o.realname, 0)
                    try:
                        usrstate = bks.objects.get(createdate__contains=date, userid=o.username, usertype=target_type)
                        usrinfo = UserInfo.objects.get(userid=o.username, usertype=target_type)
                        usr.phonenumber = usrinfo.phonenumber
                        usr.residence = usrinfo.residence
                        usr.isinschool = usrstate.get_isinschool_display()
                        usr.location = usrstate.location
                        usr.isfever = usrstate.get_isfever_display()
                        usr.is_go_to_outer = usrstate.get_is_go_to_outer_display()
                        usr.isplanedtravel = usrstate.get_isplanedtravel_display()
                        usr.ispassed = usrstate.get_ispassed_display()
                        usr.trans_type = usrstate.get_trans_type_display()
                        usr.isseen = usrstate.get_isseen_display()
                        usr.isisolated = usrstate.get_isisolated_display()
                        usr.hospital = usrstate.hospital
                        usr.is_atach_patient = usrstate.get_is_atach_patient_display()
                        usr.folk_attach = usrstate.get_folk_attach_display()
                        usr.planedtravel_time = usrstate.planedtravel_time
                        usr.plan_back_time = usrstate.plan_back_time
                        usr.planedleave_time = usrstate.planedleave_time
                    except ObjectDoesNotExist:
                        pass
                    userlist.append(usr)
        elif target_type is 2:
            dep_list = DW.objects.filter(parent=target_id)
            classmate_list = JZG.objects.filter(depid=target_id)
            for o in classmate_list:
                usr = userModel(o.userid, o.realname, 1)
                try:
                    usrstate = bks.objects.get(createdate__contains=date, userid=o.userid, usertype=1)
                    usrinfo = UserInfo.objects.get(userid=o.userid, usertype=1)
                    usr.phonenumber = usrinfo.phonenumber
                    usr.residence = usrinfo.residence
                    usr.isinschool = usrstate.get_isinschool_display()
                    usr.location = usrstate.location
                    usr.isfever = usrstate.get_isfever_display()
                    usr.is_go_to_outer = usrstate.get_is_go_to_outer_display()
                    usr.isplanedtravel = usrstate.get_isplanedtravel_display()
                    usr.ispassed = usrstate.get_ispassed_display()
                    usr.trans_type = usrstate.get_trans_type_display()
                    usr.isseen = usrstate.get_isseen_display()
                    usr.isisolated = usrstate.get_isisolated_display()
                    usr.hospital = usrstate.hospital
                    usr.is_atach_patient = usrstate.get_is_atach_patient_display()
                    usr.folk_attach = usrstate.get_folk_attach_display()
                    usr.planedtravel_time = usrstate.planedtravel_time
                    usr.plan_back_time = usrstate.plan_back_time
                    usr.planedleave_time = usrstate.planedleave_time
                except ObjectDoesNotExist:
                    pass
                userlist.append(usr)
            for dep in dep_list:
                classmate_list = JZG.objects.filter(depid=dep.bm)
                for o in classmate_list:
                    usr = userModel(o.userid, o.realname, 1)
                    try:
                        usrstate = bks.objects.get(createdate__contains=date, userid=o.userid, usertype=1)
                        usrinfo = UserInfo.objects.get(userid=o.userid, usertype=1)
                        usr.phonenumber = usrinfo.phonenumber
                        usr.residence = usrinfo.residence
                        usr.isinschool = usrstate.get_isinschool_display()
                        usr.location = usrstate.location
                        usr.isfever = usrstate.get_isfever_display()
                        usr.is_go_to_outer = usrstate.get_is_go_to_outer_display()
                        usr.isplanedtravel = usrstate.get_isplanedtravel_display()
                        usr.ispassed = usrstate.get_ispassed_display()
                        usr.trans_type = usrstate.get_trans_type_display()
                        usr.isseen = usrstate.get_isseen_display()
                        usr.isisolated = usrstate.get_isisolated_display()
                        usr.hospital = usrstate.hospital
                        usr.is_atach_patient = usrstate.get_is_atach_patient_display()
                        usr.folk_attach = usrstate.get_folk_attach_display()
                        usr.planedtravel_time = usrstate.planedtravel_time
                        usr.plan_back_time = usrstate.plan_back_time
                        usr.planedleave_time = usrstate.planedleave_time
                    except ObjectDoesNotExist:
                        pass
                    userlist.append(usr)
        elif target_type is 1:
            classmate_list = YJS.objects.filter(depid=target_id)
            for o in classmate_list:
                usr = userModel(o.userid, o.realname, 1)
                try:
                    usrstate = bks.objects.get(createdate__contains=date, userid=o.userid, usertype=1)
                    usrinfo = UserInfo.objects.get(userid=o.userid, usertype=1)
                    usr.phonenumber = usrinfo.phonenumber
                    usr.residence = usrinfo.residence
                    usr.isinschool = usrstate.get_isinschool_display()
                    usr.location = usrstate.location
                    usr.isfever = usrstate.get_isfever_display()
                    usr.is_go_to_outer = usrstate.get_is_go_to_outer_display()
                    usr.isplanedtravel = usrstate.get_isplanedtravel_display()
                    usr.ispassed = usrstate.get_ispassed_display()
                    usr.trans_type = usrstate.get_trans_type_display()
                    usr.isseen = usrstate.get_isseen_display()
                    usr.isisolated = usrstate.get_isisolated_display()
                    usr.hospital = usrstate.hospital
                    usr.is_atach_patient = usrstate.get_is_atach_patient_display()
                    usr.folk_attach = usrstate.get_folk_attach_display()
                    usr.planedtravel_time = usrstate.planedtravel_time
                    usr.plan_back_time = usrstate.plan_back_time
                    usr.planedleave_time = usrstate.planedleave_time
                except ObjectDoesNotExist:
                    pass
                userlist.append(usr)
    for index1, class__filed in enumerate(userlist):
        try:
            for index2, single in enumerate(class__filed):
                sheet.write(index1, index2, single)  # 行，列，属性值 (1,1)为B2元素，从0开始计数
        except:
            sheet.write(index1, 0, class__filed.userid)
            sheet.write(index1, 1, class__filed.realname)
            sheet.write(index1, 2, class__filed.state)
            sheet.write(index1, 3, class__filed.phonenumber)
            sheet.write(index1, 4, class__filed.isinschool)
            sheet.write(index1, 5, class__filed.residence)
            sheet.write(index1, 6, class__filed.location)
            sheet.write(index1, 7, class__filed.is_atach_patient)
            sheet.write(index1, 8, class__filed.folk_attach)
            sheet.write(index1, 9, class__filed.ispassed)
            sheet.write(index1, 10, class__filed.planedtravel_time)
            sheet.write(index1, 11, class__filed.planedleave_time)
            sheet.write(index1, 12, class__filed.isfever)
            sheet.write(index1, 13, class__filed.isseen)
            sheet.write(index1, 14, class__filed.isisolated)
            sheet.write(index1, 15, class__filed.hospital)
            sheet.write(index1, 16, class__filed.is_go_to_outer)
            sheet.write(index1, 17, class__filed.isplanedtravel)
            sheet.write(index1, 18, class__filed.trans_type)
            sheet.write(index1, 19, class__filed.plan_back_time)

    book.save(filename_or_stream=now+'.xls')

    # 利用生成器进行文件读取
    def iter_file(path):
        size = 1024
        with open(path, "rb")as f:
            for data in iter(lambda: f.read(size), b''):
                yield data

    # 以二进制形式进行数据流传输
    response = StreamingHttpResponse(iter_file(os.path.join(now+".xls")))  # 以二进制形式响应数据流
    response['Content-Type'] = 'application/octet-stream'  # 浏览器不识别的也会自动下载
    response['Content-Disposition'] = 'attachment; {}'.format(
        "filename*=utf-8''{}".format(quote("exposed_info.xls"))  # quote确保中文格式不乱码
    )
    return response
